from Crypto.Hash import MD5
from Crypto.Hash import SHA1
from Crypto.Signature import pkcs1_15
from Crypto.PublicKey import RSA
from base64 import b64encode, b64decode
import binascii
import hashlib

def sign_md5_with_private_key(sign_str, private_key_path):
    # 读取私钥文件内容
    with open(private_key_path, 'rb') as f:
        private_key = RSA.import_key(f.read())

    # 生成md5的十六进制表示
    md5_hash = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
    
    # 打印原始字符串和其 MD5 哈希值（十六进制格式）
    print("Original string:", sign_str)
    print("MD5 Hash (hex):", md5_hash)
    
    # 使用SHA1WithRSA的签名方式
    encrypt_hash = SHA1.new(md5_hash.encode('utf-8'))
    # 使用MD5WithRSA的签名方式
    #encrypt_hash = MD5.new(md5_hash.encode('utf-8'))
    signer = pkcs1_15.new(private_key)# 使用私钥进行签名
    signature = signer.sign(encrypt_hash)

    # 打印原始签名（二进制格式）和 Base64 编码后的签名
    print("Signature (binary):", binascii.hexlify(signature).decode('utf-8'))
    signature_b64 = b64encode(signature).decode('utf-8')
    print("Signature (Base64):", signature_b64)

    return signature_b64

# 测试函数
if __name__ == "__main__":
    sign_str = "app_id=10034&biz_content=DdJgKAN5j9Mut35Fv+I2irVbfn8yzr96Zxu2PftHuz0rXbfA7sVDpyBzeEQE6lZy&timestamp=2024-12-05 12:03:10"
    private_key_path = "./app_private_key.pem"

    signature = sign_md5_with_private_key(sign_str, private_key_path)